using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using ModelContextProtocol.Protocol;
using ProduceBasicData.Api.Application.Command.WarehouseManage;
using ProduceBasicData.Api.DTO.WarehouseDto;
using ProduceBasicData.Domain.WarehouseManage;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.WarehouseManage
{
    /// <summary>
    /// 获取出库单列表处理器
    /// </summary>
    public class GetStockOutOrderHandler : IRequestHandler<GetStockOutOrderCommand, ApiPaging<StockOutOrderDto>>
    {
        private readonly IBaseRespository<StockOutOrder> _stockOutOrderRepository;
        private readonly IMapper _mapper;

        public GetStockOutOrderHandler(IBaseRespository<StockOutOrder> stockOutOrderRepository, IMapper mapper)
        {
            _stockOutOrderRepository = stockOutOrderRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 处理获取出库单列表请求
        /// </summary>
        /// <param name="request">获取出库单列表命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>出库单列表结果</returns>
        public async Task<ApiPaging<StockOutOrderDto>> Handle(GetStockOutOrderCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiPaging<StockOutOrderDto>();
            try
            {
                // 构建查询条件
                var stockOutOrder = await _stockOutOrderRepository.GetAllAsync();
                var query = stockOutOrder.Where(o => !o.Isdel);

                if (!string.IsNullOrEmpty(request.OrderNumber))
                {
                    query = query.Where(o => o.OrderNumber.Contains(request.OrderNumber));
                }

                if (request.OutType.HasValue)
                {
                    query = query.Where(o => o.OutType == request.OutType.Value);
                }

                if (request.Status.HasValue)
                {
                    query = query.Where(o => o.Status == request.Status.Value);
                }

                if (request.StartDate.HasValue)
                {
                    query = query.Where(o => o.ActualOutDate >= request.StartDate.Value);
                }

                if (request.EndDate.HasValue)
                {
                    query = query.Where(o => o.ActualOutDate <= request.EndDate.Value);
                }

                if (!string.IsNullOrEmpty(request.CustomerName))
                {
                    query = query.Where(o => o.CustomerName.Contains(request.CustomerName));
                }

                // 获取总记录数
                result.TotalCount = query.Count();

                // 执行分页查询
                if (result.TotalCount > 0)
                {
                    // 应用分页
                    var pagedData = query.OrderByDescending(x => x.CreateTime)
                        .Skip((request.Index - 1) * request.Size)
                        .Take(request.Size)
                        .ToList();

                    // 映射到DTO
                    result.PageDatas = _mapper.Map<List<StockOutOrderDto>>(pagedData);
                }
                else
                {
                    result.PageDatas = new List<StockOutOrderDto>();
                }

                result.Code = ApiEnum.Success;
                result.Msg = "查询成功";
            }
            catch (Exception ex)
            {
                // 记录日志（实际项目中应使用专门的日志组件）
                // logger.LogError(ex, "仓库查询异常");

                result.Code = ApiEnum.Failed;
                result.Msg = $"查询异常: {ex.Message}";
                result.PageDatas = new List<StockOutOrderDto>();
            }

            return result;
        }
    }
}